package com.desire.k23;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * 多个消费者
 */
public class Consumers {
    /**
     * 启动两个消费者
     */
    public static void main(String[] args) {

        final String ROUTING_KEY_ORANGE = "*.orange.*";
        final String ROUTING_KEY_RABBIT = "*.*.rabbit";
        final String ROUTING_KEY_LAZY = "lazy.#";
        /**
         * 匹配一个单词。
         # 匹配0个或多个单词。
         * 消费者1的queue通过*.orange.*键绑定到exchange，
         * 消费者2的queue通过*.*.rabbit键和lazy.#键绑定到exchange
         * */

        // 消费者1
        new Thread(() -> {
            try {
                new Consumer(1, new String[]{ROUTING_KEY_ORANGE}).start();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }).start();

        // 消费者2
        new Thread(() -> {
            try {
                new Consumer(2, new String[]{ROUTING_KEY_RABBIT, ROUTING_KEY_LAZY}).start();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

/**
 * 消费者
 */
class Consumer {

    public static final String EXCHANGE_TOPIC = "exchange-topic";

    private int no = 0;
    private List<String> bindingKeys;

    public Consumer(int no, String[] bindingKeys) {
        this.no = no;
        this.bindingKeys = Arrays.asList(bindingKeys);
    }

    /**
     * 启动
     *
     * @throws IOException
     * @throws TimeoutException
     */
    public void start() throws IOException, TimeoutException {
        // 1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置虚拟主机  默认是/
        factory.setVirtualHost("erp");
        //设置mq服务器地址  默认是localhost
        factory.setHost("116.63.151.50");
        factory.setUsername("admin");
        factory.setPassword("123");
        //mq服务器的端口号
        factory.setPort(5672);
        // 2、获取连接、通道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 3、声明exchange
        channel.exchangeDeclare(EXCHANGE_TOPIC, BuiltinExchangeType.TOPIC);
        // 4、绑定queue到exchange
        String queueName = channel.queueDeclare().getQueue();
        for (String bindingKey : bindingKeys) {
            channel.queueBind(queueName, EXCHANGE_TOPIC, bindingKey);
        }

        System.out.printf("消费者 %d 等待消息%n", this.no);

        // 4、监听并消费消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.printf("消费者 %d 接受消息: %s%n", this.no, message);
            // 执行任务
            doWork(message);
            System.out.printf("消费者 %d 工作完成%n", this.no);
        };
        // 监听消息，开启自动ACK
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    }

    /**
     * 执行任务
     *
     * @param message
     */
    private void doWork(String message) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
